package com.xiangban.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiangban.aop.Permission;
import com.xiangban.model.AccompanyWallet;
import com.xiangban.model.dto.OrderDto;
import com.xiangban.model.res.ApiResult;
import com.xiangban.service.PayService;
import com.xiangban.util.WXConfigUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @Author ly
 * @date 2021/12/5 16:16
 */
@RestController
@RequestMapping("/api/wx_pay")
@Api("微信支付控制器")
@Slf4j
public class PayController {
    @Autowired
   private PayService payService;

    @PostMapping("/wx_pax")
    @ApiOperation("发起支付")
    @Permission
    public ApiResult<Object> WxPay(@RequestBody OrderDto orderDto){
        return ApiResult.newSuccess(payService.WxPay(orderDto));
    }


    @RequestMapping(value = "/wxPayNotify")
    @ResponseBody
    public String wxPayNotify(HttpServletRequest request) {
        log.info("进入回调");
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            // 将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = payService.payBack(resXml);
//            WXConfigUtil config = new WXConfigUtil();
//            WXPay wxPay = new WXPay(config);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(resXml);
            // 调用官方SDK转换成map类型数据
//            if (wxpay.isResponseSignatureValid(notifyMap)) {
            if (true) {
                // 验证签名是否有效
                String return_code = notifyMap.get("return_code");// 状态
                String out_trade_no = notifyMap.get("out_trade_no");// 商户订单号
                String attach = notifyMap.get("attach");// 商户订单号
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        log.info("===================回调成功===========");
                        //#业务逻辑处理
                        payService.businessProcessing(out_trade_no,attach);
                        log.info(JSON.toJSONString(notifyMap));
                        log.info("=======成功返回报文========"+JSON.toJSONString(result));
                    }
                }
            }
            return result;

        } catch (Exception e) {
            log.error("微信回调接口失败 error : {}", e);
            e.printStackTrace();
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            log.error(result);
            return result;
        }
    }
    @ApiOperation("提现")
    @PostMapping("wx_drawings")
    @Permission
    public ApiResult<Object> wxDrawings(@RequestBody AccompanyWallet accompanyWallet){//提现金额
       return ApiResult.newSuccess(payService.wxDrawings(accompanyWallet));
    }

}
